package impl

import (
	"context"
	"github.com/sirupsen/logrus"
	"monoblog/common"
	"monoblog/common/register"
	"monoblog/domain/dao"
	"monoblog/domain/dto"
	"monoblog/domain/model"
	"monoblog/domain/service"
)

func init() {
	register.RegisterInstance[service.AccessLogService]("AccessLogService", func() service.AccessLogService {
		return &AccessLogServiceImpl{
			accessLogRepository: dao.NewAccessLogRepository(),
		} // 返回唯一实例
	})
}

type AccessLogServiceImpl struct {
	accessLogRepository *dao.AccessLogRepository
}

func (s *AccessLogServiceImpl) Save(ctx context.Context, log *model.AccessLog) error {
	return s.accessLogRepository.Save(log)
}

func (s *AccessLogServiceImpl) FindPage(ctx context.Context, query dto.AccessLogQuery) (*common.PageData[*model.AccessLog], error) {
	query.Sort = "createTime-"

	list, count, err := s.accessLogRepository.FindList(query)
	if err != nil {
		logrus.Errorf("[aid: %s] FindPage err: %v", ctx.Value("aid"), err.Error())
		return nil, err
	}
	pageData := &common.PageData[*model.AccessLog]{}
	pageData.SetTotal(count, query.Limit())
	pageData.Records = list
	return pageData, nil
}
